#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include "text.h"

/* Read a whole file
 */
char *readfile (int fds) {
  ssize_t pos = 0;
  ssize_t size = 512;
  int cont = 1;
  char buf[500];
  ssize_t nbRead;
  char *res = (char*)malloc(size*sizeof(char));
  while(cont == 1) {
	switch (nbRead = read(fds, &buf, 500)) {
	case 0 : cont = 0; break;
	case -1 : if (errno != EINTR && errno != EIO) cont = -1; break;
	default :
	  if (pos + nbRead >= size) {
		size *= 2;
		char *tmp = (char*)malloc(size);
		memcpy(tmp, res, pos);
		free(res);
		res = tmp;
	  }
	  memcpy(res+pos, buf, nbRead);
	  pos += nbRead;
	  break;
	}
  }
  res[pos] = 0;
  return res;
}

/* find the next token in config file
 * must delete comments
 * no allocation (cf strtok); content is changed
 */
char *nextToken(char **posParse) {
  // go to the beginning of next word
  char c = ' ';
  bool cont = 1;
  while (cont) {
    if (**posParse == c || **posParse == ' ' || **posParse == '\t'
        || **posParse == '\r' || **posParse == '\n') {
      (*posParse)++;
    } else if (**posParse == '#') {
      *posParse = strchr(*posParse, '\n');
      if (*posParse == NULL) {
        return NULL;
      } else {
        (*posParse)++;
      }
    } else {
      cont=0;
    }
  }
  // find the end of this word
  char *deb = *posParse;
  if (**posParse == '\"') {
    deb++; (*posParse)++;
    while (**posParse != 0 && **posParse != '\"') (*posParse)++;
  } else {
    while(**posParse != 0 && **posParse != c && **posParse != ' '
          && **posParse != '\t' && **posParse != '\r' && **posParse != '\n') {
      (*posParse)++;
    }
    if (*posParse == deb) return NULL; // EOF
  }
  if (**posParse != 0) {
    **posParse = 0;
    (*posParse)++;
  }
  return deb;
}
